package utils;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;

public class DBconn {
    static String url = "jdbc:mysql://101.200.148.140:3306/voicerobot?serverTimezone=GMT%2B8&characterEncoding=utf8";
    static String username = "loong";
    static String password = "123";
    static Connection conn = null;
    static ResultSet rs = null;
    static PreparedStatement ps = null;

    public static void init() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            System.out.println("init [SQL驱动程序初始化失败！]");
            e.printStackTrace();
        }

    }

    public static int exec(String sql) {
        int i = 0;
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            i = ps.executeUpdate();
        } catch (SQLException e) {
            System.out.println("sql exec errror");
            e.printStackTrace();
        }
        return i;
    }

    public static ResultSet selectSql(String sql) {
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery(sql);
        } catch (SQLException e) {
            System.out.println("sql data select error!!!");
            e.printStackTrace();
        }
        return rs;
    }

    public static void closeConn() {
        try { // 捕捉异常
            if (rs != null) { // 当ResultSet对象的实例rs不为空时
                rs.close(); // 关闭ResultSet对象
            }
            if (ps != null) { // 当Statement对象的实例stmt不为空时
                ps.close(); // 关闭Statement对象
            }
            if (conn != null) { // 当Connection对象的实例conn不为空时
                conn.close(); // 关闭Connection对象
            }
        } catch (Exception e) {
            System.out.println("sql数据库关闭异常");
            e.printStackTrace(System.err); // 输出异常信息
        }
    }
}